<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
  var list = [
    {id: '1', pid: '', name: '总裁办'},
    {id: '2', pid: '', name: '行政部'},
    {id: '3', pid: '', name: '人事部'},
    {id: '4', pid: '', name: '财务部'},
    {id: '5', pid: '4', name: '出纳'},
    {id: '6', pid: '4', name: '审计'},
    {id: '7', pid: '2', name: '学工'},
    {id: '8', pid: '1', name: '教研部'},
    {id: '9', pid: '8', name: 'java'},
    {id: '10', pid: '8', name: '前端'},
    {id: '11', pid: '8', name: 'python'}
  ]
  // 转成树状的数据
  function listToTree (list, pid = '') {
    const arr = []
    list.forEach(item => {
      if (item.pid === pid) {
        arr.push(item)
        const children = listToTree(list, item.id)
        if (children.length) {
          item.children = children
        }
      }
    })
    return arr
  }

  const result = listToTree(list)
  console.log(result)
  /**
 * 将列表转成树形数据
 * @param {Array} list 数组
 * @param {String} pid 父组件id
 */
// export function listToTree(list, pid = '') {
//   const arr = []
//   list.forEach(item => {
//     if (item.pid === pid) {
//       arr.push(item)
//       const children = listToTree(list, item.id)
//       if (children.length) {
//         item.children = children
//       }
//     }
//   })
//   return arr
// }
</script>
</body>
</html>
